/**
 * 
 */
package org.going.utils;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.going.factory.ParamValueGeneratorFactory;
import org.going.invoker.ParamValueGenerateException;

/**
 * @author ferendo.huang@gmail.com
 * 
 */
public class RequestUtils implements GoingConst
{
	@SuppressWarnings("unchecked")
	public static <T> T[] generatePojoArray(String prefix, Class<T> clazz, HttpServletRequest request) throws InstantiationException, IllegalAccessException
	{
		String num = request.getParameter(prefix);
		if (StringUtils.empty(num) || ZERO.equals(num))
		{
			return null;
		}
		List<T> list = new ArrayList<T>();
		int count = Integer.valueOf(num);
		String pre = prefix.substring(0, prefix.length() - 2);
		for (int i = 0; i < count; i++)
		{
			String arrPrefix = pre + i + BRACKET_RIGHT + DOT;
			list.add(generatePojo(arrPrefix, clazz, request));
		}
		return list.toArray((T[]) Array.newInstance(clazz, 0));
	}

	public static <T> T generatePojo(String prefix, Class<T> clazz, HttpServletRequest request)
			throws InstantiationException, IllegalAccessException
	{
		String arrPrefix = prefix + DOT;
		return generatePojoImpl(arrPrefix, clazz, request);
	}

	private static <T> T generatePojoImpl(String arrPrefix, Class<T> clazz, HttpServletRequest request)
			throws InstantiationException, IllegalAccessException
	{
		T obj = clazz.newInstance();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields)
		{
			Class<?> fieldClass = field.getType();
			String fieldStr = arrPrefix + field.getName();
			try
			{
				field.setAccessible(true);
				try
				{
					// use the ParamValueGenerator to generate the value...
					Object val = ParamValueGeneratorFactory.getValueGenerator(fieldClass).generate(fieldStr,
							fieldClass, request);
					if (val == null)
						continue;
					field.set(obj, val);
				}
				catch (ParamValueGenerateException e)
				{
					throw new InstantiationException(" Error occur while generating the value of POJO :: " + fieldStr);
				}
			}
			finally
			{
				field.setAccessible(false);
			}
		}
		return obj;
	}
}
